package com.suse.jd_system_server.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JwtUtils {
    private static final String secret="thomas";//密钥
    //创建Jwt
    public String createJwt(Integer userId, String userName, List<String> authList){
        Date issDate = new Date();//签发时间时间
        Date expireDate = new Date(issDate.getTime()+1000*60*60*2);//当前时间加上两小时
        Map<String,Object> headerClaims = new HashMap<>();
        headerClaims.put("alg","HS256");
        headerClaims.put("typ","JWT");
        return JWT.create().withHeader(headerClaims)
                .withIssuer("pb")//设置签发人
                .withIssuedAt(issDate)//签发时间
                .withExpiresAt(expireDate)//设置过期时间
                .withClaim("userId",userId)//自定义声明 用户Id
                .withClaim("userName",userName)//自定义声明 用户名
//                .withClaim("userAuth",authList)//自定义声明  用户权限
                .sign(Algorithm.HMAC256(secret));//使用HS265进行签名，使用secret作为密钥
    }
    //校验Jwt
    public boolean verifToken(String jwtToken){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            //校验token
            DecodedJWT decodedJWT = jwtVerifier.verify(jwtToken);
            Integer userId = decodedJWT.getClaim("userId").asInt();
            String userName = decodedJWT.getClaim("userName").asString();
            List<String> userAuthList = decodedJWT.getClaim("userAuth").asList(String.class);
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return false;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 从jwt的payload里获取声明，获取的用户Id
     * @param jwt
     * @return
     */
    public DecodedJWT getUserFromToken(String jwt){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            //校验token
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
//            return decodedJWT.getClaim("userId").asInt();
            Integer userId = decodedJWT.getClaim("userId").asInt();
            String userName = decodedJWT.getClaim("userName").asString();
            List<String> userAuthList = decodedJWT.getClaim("userAuth").asList(String.class);
            return decodedJWT;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
